package com.jay.tools.recycler;

import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;

/**
 * Created by tan on 2017/9/20 020.
 * RecyclerView的业务bean
 */

public class MultipleItemEntity implements MultiItemEntity, Comparable<MultipleItemEntity> {

    //数据了过大时RecyclerView有可能会内存泄漏，引入此可以对内存进行释放
    private final ReferenceQueue<LinkedHashMap<Object, Object>> ITEM_QUENE = new ReferenceQueue<>();
    //存储每个加入数据的键值对
    private final LinkedHashMap<Object, Object> MULTIPLE_FIELDS = new LinkedHashMap<>();

    private final SoftReference<LinkedHashMap<Object, Object>> FIELDS_REFERENCE
            = new SoftReference<>(MULTIPLE_FIELDS, ITEM_QUENE);

    // 再次强调，使用构建者模式，宿主类不能被外部new因此这里限定为包内访问
    MultipleItemEntity(LinkedHashMap<Object, Object> fields) {
        FIELDS_REFERENCE.get().putAll(fields);
    }

    public static MultipleItemEntityBuilder builder() {
        return new MultipleItemEntityBuilder();
    }

    //实现RecyclerView的样式类型
    @Override
    public int getItemType() {
        return (int) FIELDS_REFERENCE.get().get(MultipleFields.ITEM_TYPE);
    }

    @SuppressWarnings("unchecked")
    public final <T> T getField(Object key) {
        return (T) FIELDS_REFERENCE.get().get(key);
    }

    public final LinkedHashMap<?, ?> getFields() {
        return FIELDS_REFERENCE.get();
    }

    public final MultipleItemEntity setField(Object key, Object value) {
        FIELDS_REFERENCE.get().put(key, value);
        return this;
    }

    /**
     * 按类型进行升序排列
     */
    @Override
    public int compareTo(MultipleItemEntity entity) {
        return getItemType() - entity.getItemType();
    }
}
